﻿namespace TPO.UI
{
    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Windows.Forms;
    using System.Runtime.InteropServices;

    public unsafe class richbox : RichTextBox
    {
        [DllImport("user32")]
        private static extern int GetScrollPos(IntPtr hWnd, Int32 nBar);
        [DllImport("user32")]
        private static extern bool GetScrollRange(IntPtr hWnd, Int32 nBar, int* min, int* max);
        [DllImport("user32")]
        private static extern bool GetScrollInfo(IntPtr hWnd, Int32 nBar, SCROLLINFO* si);

        private const Int32 WM_VSCROLL = 0x00000115;
        private const Int32 SB_VERT = 0x00000001;
        //private IntPtr handle = IntPtr.Zero;
        private int max, min, pos;
        private uint page;

        public int VScrollMax
        {
            get { updatedata(); return max; }
            //get
            //{
            //    int max, min;
            //    GetScrollRange(Handle, SB_VERT, &min, &max);
            //    return max;
            //}
        }

        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
        public struct SCROLLINFO
        {
            public uint cbSize;
            public uint fMask;
            public int nMin;
            public int nMax;
            public uint nPage;
            public int nPos;
            public int nTrackPos;
        }

        public int VScrollMin
        {
            get { updatedata(); return min; }
            //get
            //{
            //    int max, min;
            //    GetScrollRange(Handle, SB_VERT, &min, &max);
            //    return min;
            //}
        }

        public uint nPage
        {
            get
            {
                updatedata(); return page;
            }
        }

        public int VScrollPos
        {
            get { updatedata(); return pos; }
        }

        void updatedata()
        {
            SCROLLINFO si = new SCROLLINFO();
            si.cbSize = (uint)sizeof(SCROLLINFO);
            si.fMask = 0x17;//SIF_ALL
            GetScrollInfo(Handle, SB_VERT, &si);
            pos = si.nPos;
            page = si.nPage;
            max = si.nMax;
            min = si.nMin;
        }

        protected override void WndProc(ref Message m)
        {
            if (m.Msg == WM_VSCROLL)
            {
                //int position = GetScrollPos(m.HWnd, SB_VERT);
                OnVScroll(new EventArgs());
            }

            base.WndProc(ref m);
        }
    }
}